package com.ebeitech.auction.view.homepage;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.ebeitech.auction.R;
import com.ebeitech.auction.bean.Auction;
import com.ebeitech.auction.bean.AuctionBidder;
import com.ebeitech.auction.bean.AuctionPhase;
import com.ebeitech.auction.constants.CommonConstants;
import com.ebeitech.auction.domain.ChatMessage;
import com.ebeitech.auction.http.EbeiErrorCode;
import com.ebeitech.auction.http.HttpService;
import com.ebeitech.auction.http.model.AuctionModel;
import com.ebeitech.auction.http.service.HttpAuctionServiceRx;
import com.ebeitech.auction.view.auction.AuctionDetailActivity;
import com.ebeitech.library.constant.MessageConstants;
import com.ebeitech.library.constant.SPConstants;
import com.ebeitech.library.ui.pulltorefresh.PullToRefreshBase;
import com.ebeitech.library.ui.pulltorefresh.PullToRefreshListView;
import com.ebeitech.library.util.SPManager;
import com.ebeitech.library.util.StringUtil;
import com.ebeitech.library.util.TimeUtil;
import com.ebeitech.library.util.ViewUtil;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.ResponseBody;
import retrofit2.Call;

/**
 * Created by alice on 2017/10/31.
 */
public class AuctionListFragment extends Fragment {

	@BindView(R.id.listView)
	PullToRefreshListView mPullToRefreshListView;
	ListView mListView;
	Unbinder unbinder;

	private int mCurrentTab;
	private Context mContext;
	private BaseAdapter mAdapter;
	private List<Auction> mAuctionList = new ArrayList<Auction>();
	private ViewGroup mEmptyView;

	private int mCurrentPage = 1;
	private int mLastPage = -1;
	private boolean isRefreshing;
	private boolean isOncreateView;// 是否调用过oncreateView
	private boolean isViewRefreshed = false;// 保证每次重新进入都要刷新

	public void setCurrentTab(int currentTab) {
		mCurrentTab = currentTab;
	}

	private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent != null) {
				String action = intent.getAction();
				if (MessageConstants.ACTION_MESSAGE_RECEIVE.equals(action)) {
					ChatMessage chatMessage = (ChatMessage) intent.getSerializableExtra(MessageConstants.MESSAGE);
					if (chatMessage != null) {
						if (ChatMessage.MESSAGE_TYPE_OUR_PRICE_RECALL.equals(chatMessage.getMessageType())) {
							// 如果消息是撤回,就不管最高价,直接用撤回消息里返回的价格
							Auction auction = new Auction();
							auction.setAuctionId(chatMessage.getAuctionId());
							int index = mAuctionList.indexOf(auction);
							if (index > -1) {
								auction = mAuctionList.get(index);
								AuctionPhase mAuctionPhase = auction.getCurrentAuctionPhase();
								if (mAuctionPhase != null) {
									mAuctionPhase.setPhaseResult(chatMessage.getPrice());
									mAuctionPhase.setPhaseResultRate(chatMessage.getPhaseResultRate());
									mAuctionPhase.setPhaseOurResult(chatMessage.getPhaseOurResult());
									mAuctionPhase.setPhaseOurResultRate(chatMessage.getPhaseOurResultRate());
									mAdapter.notifyDataSetChanged();
								}
							}
						} else if (ChatMessage.MESSAGE_TYPE_OUR_PRICE.equals(chatMessage.getMessageType())
								|| ChatMessage.MESSAGE_TYPE_THEIR_PRICE.equals(chatMessage.getMessageType())) {
							// 如果消息是出价的消息,要更新现有的报价
							Auction auction = new Auction();
							auction.setAuctionId(chatMessage.getAuctionId());
							int index = mAuctionList.indexOf(auction);
							if (index > -1) {
								auction = mAuctionList.get(index);
								AuctionPhase mAuctionPhase = auction.getCurrentAuctionPhase();
								if (mAuctionPhase != null) {
									// 如果是递增,新的报价必须大于当前报价;递减的话必须小于
									boolean isValid = false;
									float oldResult = 0, newResult = 0;
									try {
										oldResult = Float.valueOf(mAuctionPhase.getPhaseResult());
										newResult = Float.valueOf(chatMessage.getPrice());
									} catch (Exception e) {}
									if (AuctionPhase.QUOTES_TYPE_ADD.equals(mAuctionPhase.getQuotesTypeCode()) && newResult > oldResult) {
										isValid = true;
									} else if (AuctionPhase.QUOTES_TYPE_MINUS.equals(mAuctionPhase.getQuotesTypeCode()) && newResult < oldResult) {
										isValid = true;
									}
									if (!isValid) {
										return;
									}

									mAuctionPhase.setPhaseResult(chatMessage.getPrice());
									mAuctionPhase.setPhaseResultRate(chatMessage.getPhaseResultRate());
									AuctionBidder resultBidder = new AuctionBidder();
									resultBidder.setBidderAuctionCode(chatMessage.getAuctionBidderCode());
									resultBidder.setBidderName(chatMessage.getBidderName());
									mAuctionPhase.setResultBidder(resultBidder);
									if (ChatMessage.MESSAGE_TYPE_OUR_PRICE.equals(chatMessage.getMessageType())) {
										mAuctionPhase.setPhaseOurResult(chatMessage.getPrice());
										mAuctionPhase.setPhaseOurResultRate(chatMessage.getPhaseResultRate());
									}
									mAdapter.notifyDataSetChanged();
								}
							}
						} else if (ChatMessage.MESSAGE_TYPE_PHASE_SWITCH.equals(chatMessage.getMessageType())) {
							// 如果消息是阶段切换的消息,要更新阶段
							Auction auction = new Auction();
							auction.setAuctionId(chatMessage.getAuctionId());
							int index = mAuctionList.indexOf(auction);
							if (index > -1) {
								auction = mAuctionList.get(index);
								AuctionPhase mAuctionPhase = auction.getCurrentAuctionPhase();
								if (mAuctionPhase == null) {
									mAuctionPhase = new AuctionPhase();
								}

								mAuctionPhase.setPhaseState("0");
								List<AuctionPhase> auctionPhases = auction.getAuctionPhases();
								boolean isFirstBegin = false, isEnd = false;
								for (int i = 0; i < auctionPhases.size(); i++) {
									AuctionPhase auctionPhase = auctionPhases.get(i);
									if (StringUtil.getDefaultString(chatMessage.getNextPhaseId()).equals(auctionPhase.getPhaseId())) {
										// 看看是不是大于当前阶段
										if (i > 0 && !(mAuctionPhase.getPhaseSort() < auctionPhase.getPhaseSort())) {
											return;
										}

										auctionPhase.setPhaseState("1");
										auctionPhase.setPhaseResult(auctionPhase.getStartPrice());
										auctionPhase.setPhaseOurResult(auctionPhase.getStartPrice());
										// 如果是第一个阶段开始,就把拍卖状态改为进行中
										if (i == 0) {
											isFirstBegin = true;
										}
									}
									if (StringUtil.getDefaultString(chatMessage.getPhaseId()).equals(auctionPhase.getPhaseId())) {
										// 如果是最后一个阶段结束,就把拍卖状态改为结束
										if (i == auctionPhases.size() - 1) {
											isEnd = true;
										}
									}
								}
								if (isFirstBegin) {
									auction.setStateCode(CommonConstants.STATE_BEGINNING);
								} else if (isEnd) {
									auction.setStateCode(CommonConstants.STATE_FINISHED);
									// 结束的时候,删除下无效信息
									SPManager.getInstance().remove(auction.getAuctionId() + "_" + SPConstants.BIDDER_CODE);
								}
								mAdapter.notifyDataSetChanged();
							}
						}
					}
				} else if (MessageConstants.ACTION_MESSAGE_INFO_CHANGE.equals(action)) {
					// 更新竞拍人信息
					Auction auction = (Auction) intent.getSerializableExtra(CommonConstants.AUCTION);
					if (action != null) {
						updateAuctionInfo(auction);
					}
				}
			}
		}
	};

	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		isOncreateView = true;
		mContext = getActivity();
		View view = inflater.inflate(R.layout.ebei_activity_pulltorefreshlistview, null);
		unbinder = ButterKnife.bind(this, view);
		initView(view);
		if (mCurrentTab == HomepageActivity.TAB_TODAY) {
			registerBroadCast();
		}
		return view;
	}

	private void initView(View view) {
		view.findViewById(R.id.view_title).setVisibility(View.GONE);
		mListView = mPullToRefreshListView.getRefreshableView();
		mListView.setDivider(null);
		mAdapter = new AuctionAdapter(mContext, mCurrentTab, mAuctionList);
		mListView.setAdapter(mAdapter);
		mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if (!(position > -1 && position < mAuctionList.size())) {
					return;
				}

				Intent intent = new Intent(mContext, AuctionDetailActivity.class);
				intent.putExtra("currentTab", mCurrentTab);
				intent.putExtra(CommonConstants.AUCTION, mAuctionList.get(position));
				startActivity(intent);
			}
		});

		mPullToRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
			@Override
			public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
				if (!isRefreshing) {
					isRefreshing = true;
					mCurrentPage = 1;
					mLastPage = -1;
					loadList();
				} else {
					mPullToRefreshListView.onPullDownRefreshComplete();
					isRefreshing = false;
				}
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
				if (mCurrentPage != mLastPage) {
					if (!isRefreshing) {
						isRefreshing = true;
						mCurrentPage++;
						loadList();
					}
				} else {
					mPullToRefreshListView.onPullUpRefreshComplete();
					Toast.makeText(mContext, R.string.ebei_pull_to_refresh_to_end, Toast.LENGTH_SHORT).show();
					isRefreshing = false;
				}
			}
		});

		LinearLayout emptyParentView = new LinearLayout(mContext);
		emptyParentView.setOrientation(LinearLayout.VERTICAL);
		emptyParentView.setGravity(Gravity.CENTER);
		ImageView emptyImage = new ImageView(mContext);
		emptyImage.setImageResource(R.drawable.ebei_btn_not_begin);
		emptyParentView.addView(emptyImage);
		TextView emptyText = new TextView(mContext);
		if (mCurrentTab == HomepageActivity.TAB_TODAY) {
			emptyText.setText(R.string.ebei_auction_no_data_today);
		} else {
			emptyText.setText(R.string.ebei_auction_no_data);
		}
		emptyText.setTextColor(getResources().getColor(R.color.ebei_text_common_light));
		emptyText.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.ebei_common_text_size));
		emptyText.setPadding(0, ViewUtil.dp2px(mContext, 10), 0, ViewUtil.dp2px(mContext, 10));
		emptyText.setGravity(Gravity.CENTER_HORIZONTAL);
		emptyParentView.addView(emptyText);

		mEmptyView = emptyParentView;
		mEmptyView.setLayoutParams(new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams.MATCH_PARENT));

		final View view_content = view.findViewById(R.id.view_content);
		ViewTreeObserver vto = view_content.getViewTreeObserver();
		vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
			@Override
			public void onGlobalLayout() {
				view_content.getViewTreeObserver().removeGlobalOnLayoutListener(this);

				AbsListView.LayoutParams lp = (AbsListView.LayoutParams) mEmptyView.getLayoutParams();
				lp.height = view_content.getMeasuredHeight();
				mEmptyView.setLayoutParams(lp);
			}
		});
	}

	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		super.setUserVisibleHint(isVisibleToUser);
		if (isVisibleToUser) {
			if (isOncreateView) {
				isViewRefreshed = true;
				isRefreshing = false;
				mPullToRefreshListView.doPullRefreshing(true, 300);
			}
		} else {
			isViewRefreshed = false;
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		if (isViewRefreshed) {
			return;
		}
		isRefreshing = false;
		mPullToRefreshListView.doPullRefreshing(true, 300);
	}

	@Override
	public void onPause() {
		super.onPause();
		isViewRefreshed = false;
	}

	private void registerBroadCast() {
		IntentFilter myIntentFilter = new IntentFilter();
		myIntentFilter.addAction(MessageConstants.ACTION_MESSAGE_RECEIVE);
		myIntentFilter.addAction(MessageConstants.ACTION_MESSAGE_INFO_CHANGE);
		mContext.registerReceiver(mBroadcastReceiver, myIntentFilter);
	}


	@Override
	public void onDestroyView() {
		super.onDestroyView();
		isOncreateView = false;
		if (mCurrentPage == HomepageActivity.TAB_TODAY) {
			mContext.unregisterReceiver(mBroadcastReceiver);
		}
	}

	private void loadList() {
		Map<String, String> params = new HashMap<String, String>();
		params.put("pageIndex", String.valueOf(mCurrentPage));
		params.put("pageSize", String.valueOf(CommonConstants.PAGE_SIZE));
		String startDate = "", endDate = "", states = "";
		if (mCurrentTab == HomepageActivity.TAB_TODAY) {
			startDate = TimeUtil.getCurrentDay() + " 00:00:00";
			endDate = TimeUtil.getCurrentDay() + " 23:59:59";
			states = CommonConstants.STATE_PUBLISHED + "," + CommonConstants.STATE_BEGINNING;
			params.put("endDate", endDate);
		} else if (mCurrentTab == HomepageActivity.TAB_BEGIN) {
			startDate = TimeUtil.getDayStrFromTime(TimeUtil.getTimeWithDiff(TimeUtil.getCurrentTime(), 1, TimeUtil.UNIT_DAY)) + " 00:00:00";
			states = CommonConstants.STATE_PUBLISHED;
			params.put("startDate", startDate);
		} else if (mCurrentTab == HomepageActivity.TAB_FINISH) {
			states = CommonConstants.STATE_FINISHED;
		}
		states = "[" + states + "]";
		params.put("states", states);

		HttpService mHttpService = HttpService.getInstance();
		HttpAuctionServiceRx mHttpAuctionServiceRx = mHttpService.getRxGsonRetrofit().create(HttpAuctionServiceRx.class);
		final Call<ResponseBody> mCall = mHttpAuctionServiceRx.doLoadTodayList(params);
		mHttpService.executeHttp(mContext, mCall, new HttpService.HttpListener<AuctionModel>() {
			@Override
			public void onStart() {

			}

			@Override
			public void onError(EbeiErrorCode errorCode) {
				finished();
			}

			@Override
			public void onSuccess(AuctionModel baseModel) {
				if (mCurrentPage == 1) {
					mAuctionList.clear();
				}
				List<Auction> list = baseModel.getAuctions();
				if (list != null && list.size() > 0) {
					mAuctionList.addAll(list);
				} else {
					mLastPage = mCurrentPage;
				}

				if (mAuctionList.size() == 0) {
					mListView.setAdapter(null);//为了兼容4.3以前的手机
					mListView.removeHeaderView(mEmptyView);
					mListView.addHeaderView(mEmptyView);
				} else {
					mListView.removeHeaderView(mEmptyView);
				}
				if (mListView.getAdapter() == null) {
					mListView.setAdapter(mAdapter);
				} else {
					mAdapter.notifyDataSetChanged();
				}
				finished();
			}
		}, AuctionModel.class);
	}

	private void finished() {
		mPullToRefreshListView.onPullDownRefreshComplete();
		mPullToRefreshListView.onPullUpRefreshComplete();
		isRefreshing = false;
	}

	private void updateAuctionInfo(final Auction auction) {
		// 先调用接口拉下最新的数据
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("auctionId", auction.getAuctionId());

		HttpService mHttpService = HttpService.getInstance();
		HttpAuctionServiceRx mHttpAuctionServiceRx = mHttpService.getRxGsonRetrofit().create(HttpAuctionServiceRx.class);
		final Call<ResponseBody> call = mHttpAuctionServiceRx.getMessageByWeb(params);
		mHttpService.executeHttp(mContext, call, new HttpService.HttpListener<String>() {
			@Override
			public void onStart() {
			}

			@Override
			public void onError(EbeiErrorCode errorCode) {
			}

			@Override
			public void onSuccess(final String result) {
				new AsyncTask<Void, Void, Void>() {

					List<ChatMessage> messages;

					@Override
					protected Void doInBackground(Void... params) {
						if (!StringUtil.isEmpty(result)) {
							try {
								Auction auction = new Gson().fromJson(result, Auction.class);
								if (auction != null) {
									int index = mAuctionList.indexOf(auction);
									if (index > -1) {
										mAuctionList.set(index, auction);;
										mListView.post(new Runnable() {
											@Override
											public void run() {
												mAdapter.notifyDataSetChanged();
											}
										});
									}
								}
							} catch (Exception e) {}
						}
						return null;
					}

					@Override
					protected void onPostExecute(Void aVoid) {
						super.onPostExecute(aVoid);
					}
				}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
			}
		}, String.class, false);
	}

}
